package com.baor.aspectj;


import com.baor.dao.SyslogDao;
import com.baor.domain.SyslogVo;
import com.baor.domain.LoginUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import static com.baor.utils.DateUtil.now;

@Aspect
@Component
public class LogAspect {

    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<>("Cost Time");

    @Autowired
    private SyslogDao syslogDao;

    @Pointcut("execution(* com.baor.service..*.*(..))")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        //获取当前请求路径
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestPath = attributes.getRequest().getRequestURI();

        //方法主体执行之前
        TIME_THREADLOCAL.set(System.currentTimeMillis());

        Object proceed = pjp.proceed();

        //方法主体执行之后
        try{
            SyslogVo vo = new SyslogVo();
            vo.setSyslogPeriod(System.currentTimeMillis() - TIME_THREADLOCAL.get());
            vo.setSyslogCreatetime(now());
            vo.setSyslogOperate(requestPath);
            LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            vo.setSyslogUser(syslogDao.selectUserName(loginUser.getUserVo().getUserId()));
            syslogDao.insert(vo);
        } catch (Exception ex){
            System.out.println("异常信息:{}"+ ex.getMessage());
            ex.printStackTrace();
        } finally{
            TIME_THREADLOCAL.remove();
        }
        return proceed;
    }



}
